﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows;

namespace ExtendedEditor.Painter
{
	public static class PainterExtensions
	{
		#region Paragraph extension

		public static double GetWidth(this Paragraph par)
		{
			double width = 0;

			foreach (Run item in par.Inlines)
			{
				Typeface typeface = new Typeface(
					item.FontFamily,
					item.FontStyle,
					item.FontWeight,
					item.FontStretch);
				FormattedText ft = new FormattedText(
					item.Text,
					System.Globalization.CultureInfo.CurrentCulture,
					FlowDirection.LeftToRight,
					typeface,
					item.FontSize, Brushes.Black);
				ft.MaxLineCount = 1;
				width += ft.WidthIncludingTrailingWhitespace;
			}
			return width;
		}

		public static Paragraph GetNextParagraph(this Paragraph par, LogicalDirection dirrection)
		{
			Paragraph result = null;
			if (dirrection == LogicalDirection.Forward)
			{
				TextPointer pt = par.ElementEnd;
				pt = pt.GetNextContextPosition(LogicalDirection.Forward);
				if (pt != null) result = pt.Paragraph;
			}
			else
			{
				TextPointer pt = par.ElementStart;
				pt = pt.GetNextContextPosition(LogicalDirection.Backward);
				if (pt != null) result = pt.Paragraph;
			}

			return result;
		}

		#endregion

		#region FlowDocument extension

		public static Paragraph[] GetParagraphRange(this FlowDocument document, TextPointer start, TextPointer end)
		{
			List<Paragraph> result = new List<Paragraph>();
			Paragraph cur = null;
			while (true)
			{
				cur = start.Paragraph;
				if (cur == null) start = start.GetNextContextPosition(LogicalDirection.Forward);
				else break;

				if (start == null) break;
			}

			while (true)
			{
				bool match = false;
				if (cur != null)
				{
					match = match || (start.CompareTo(cur.ElementStart) >= 0 && start.CompareTo(cur.ElementEnd) <= 0);
					match = match || (end.CompareTo(cur.ElementStart) >= 0 && end.CompareTo(cur.ElementEnd) <= 0);
					match = match || (start.CompareTo(cur.ElementStart) <= 0 && end.CompareTo(cur.ElementEnd) >= 0);
				}
				if (match)
				{
					result.Add(cur);
					cur = cur.GetNextParagraph(LogicalDirection.Forward);
				}
				else break;

			}

			return result.ToArray();
		}

		#endregion
	}
}
